
import "package:collection/collection.dart";
import 'package:factoryside/api/api.dart';
import 'package:factoryside/bean/finance_entity.dart';
import 'package:factoryside/bean/finances_json_entity.dart';
import 'package:factoryside/bean/recharge_record_entity.dart';
import 'package:factoryside/generated/json/finance_entity_helper.dart';
import 'package:factoryside/generated/json/recharge_record_entity_helper.dart';
import 'package:factoryside/home/page_order_detail.dart';
import 'package:factoryside/provider/providers.dart';
import 'package:factoryside/utils/ColorsUtils.dart';
import 'package:factoryside/utils/request_util.dart';
import 'package:factoryside/utils/utils.dart';
import 'package:factoryside/widget/tabs.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_my_picker/common/date.dart';
import 'package:flutter_my_picker/flutter_my_picker.dart';
import 'package:flutter_sticky_header/flutter_sticky_header.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

///账单流水明细

class BillPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _BillState();
  }
}

class _BillState extends State<BillPage>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  TabController _tabController;

  List<Widget> SubPages=[];

  @override
  void dispose() {
    super.dispose();
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  var myTabs = <Tab>[
    Tab(
      text: '充值记录',
    ),
    Tab(
      text: '进行中暂冻结',
    ),
    Tab(
      text: '待结算',
    ),
    Tab(
      text: '已结算',
    ),
  ];
  var states=['23','2','3'];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    SubPages.add(BillRechargeSubPage());
    //需要查询的类型 0：全部 1充值 2支出 3提现 5收入 8退款
    SubPages.addAll(states.map((e) => BillSubPage(e)).toList());
    this._tabController = new TabController(vsync: this, length: myTabs.length);
    this._tabController.addListener(() {
//      context.watch<MyProvider>().changeDateStr(MyDate.format('yyyy-MM', DateTime.now()),states[_tabController.index]);
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); //必须实现 不然 在push过后页面会刷新
    // TODO: implement build

    return Scaffold(
        appBar: buildAppBar('明细', null, context),
        body: Column(
          children: [
            buildTabBar(),
            Expanded(
              child: ExtendedTabBarView(
                controller: _tabController,
                children: SubPages,
              ),
            ),
          ],
        ));
  }

  Widget buildTabBar() {
    return Container(
      color: Colors.white,
      child: TabBar(
        controller: _tabController,
        isScrollable: true,
        onTap: (int index) {
          print('Selected......$index');
        },
        unselectedLabelColor: Colors.black, //设置未选中时的字体颜色，tabs里面的字体样式优先级最高
        unselectedLabelStyle:
            TextStyle(fontSize: 15), //设置未选中时的字体样式，tabs里面的字体样式优先级最高
        labelColor: Colors.black, //设置选中时的字体颜色，tabs里面的字体样式优先级最高
        labelStyle: TextStyle(
            fontSize: 15.0,
            fontWeight: FontWeight.bold), //设置选中时的字体样式，tabs里面的字体样式优先级最高
        indicatorColor: Colors.blue, //选中下划线的颜色
        indicatorSize: TabBarIndicatorSize
            .label, //选中下划线的长度，label时跟文字内容长度一样，tab时跟一个Tab的长度一样
        indicatorWeight: 2.0, //选中下划线的高度，值越大高度越高，默认为2。0
        indicator: BoxDecoration(), //用于设定选中状态下的展示样式
        tabs: myTabs,
      ),
    );
  }

}

class BillRechargeSubPage extends StatefulWidget {

  BillRechargeSubPage();

  @override
  _BillRechargeSubPageState createState() => _BillRechargeSubPageState();
}

class _BillRechargeSubPageState extends State<BillRechargeSubPage>
    with AutomaticKeepAliveClientMixin {

  var date = DateTime.now();
  var end = DateTime.now();
  var dateStr = MyDate.format('yyyy-MM', DateTime.now());
  var totalTxt='';

  var page = 1;
  var limit = 10;
  List<RechargeRecordEntity> items = [];
  Map<String, List<RechargeRecordEntity>> sections=Map();
  List<double> inList=[];
  RefreshController _refreshController =
  RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  void _fetchData() {
    RequestUtil.post(Api.newRechargeRecord, {
      "page":page,
      "limit":limit,
      "UserID":Api.userName,
      "State":1,
      "PayTypeCode":"",
      "CreateTimeStart":"",
      "CreateTimeEnd":""
    }).then((value) => this.setState(() {
      List list = value['Data']['Item1'];
      List<RechargeRecordEntity> billList = [];
      list.forEach((element) {
        billList.add(rechargeRecordEntityFromJson(RechargeRecordEntity(),element));
      });
      if (page == 1) {
        items = billList;
        _refreshController.resetNoData();
      } else {
        if (billList.length == 0) {
          _refreshController.loadNoData();
        } else {
//              Year=2021;
//              Month=12-page;
//              for(int i=0;i<10;i++){
//                items.add(Bill(BillSecEntity.init(24244, 0, '', '2424420210416115558', '$Year-$Month-16 11:55:58', (10+i).toDouble(), '收入', '2', false),false));
//              }
          items.addAll(billList);
        }
      }
      ///按月份分组
      sections = groupBy(items, (bill) => bill.createTime.substring(0,bill.createTime.lastIndexOf('-')));
    }));
  }

  @override
  void dispose() {
    print('dispose');
    _refreshController.dispose();
    super.dispose();
  }
  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  void _onRefresh() async {
    await Future.delayed(Duration(milliseconds: 1000));
    page = 1;
    _fetchData();
    _refreshController.resetNoData();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    await Future.delayed(Duration(microseconds: 1000));

    page++;
    _fetchData();
    _refreshController.loadComplete();
  }


  @override
  Widget build(BuildContext context) {
    super.build(context); //必须实现 不然 在push过后页面会刷新
    return buildBody();
  }

  Widget buildBody() {
    return DefaultStickyHeaderController(
      child: Container(
        padding: EdgeInsets.only(top: 10),
        color: ColorsUtil.hexToColor('#F2F2F2'),
        child: Column(
          children: [
            buildContainer(),
            Expanded(
              child: items.length == 0
                  ? buildSmartRefresher(buildEmptyContainer())
                  : buildSmartRefresher(CustomScrollView(
                slivers: sections.keys.toList().asMap().keys.map((index) => _RechargeStickyHeaderList(sections: sections,index: index,list: sections[sections.keys.toList()[index]],title: sections.keys.toList()[index])).toList(),
              )),
            )
          ],
        ),
      ),
    );
  }

  Widget buildContainer() {
    return Consumer<Bill>(builder: (context,provider,widget){
      inList.clear();
      totalTxt='总充值￥0';
      var date=provider.dateStr;
      if(date!=null){
        dateStr=date;
        if (sections[dateStr]!=null) {
          sections[dateStr].forEach((element) {
            inList.add(element.payMoney);
          });
        }
      }
      totalTxt='总充值￥${inList.sum.toStringAsFixed(2)}';
      return Container(
        color: Colors.white,
        padding: EdgeInsets.all(10),
        child: Row(
          children: [
            InkWell(
              onTap: updateTime,
              child: Row(
                children: [
                  Text(dateStr, style: TextStyle(color: Colors.blue)),
                  Icon(
                    Icons.arrow_drop_down,
                    color: Colors.blue,
                  )
                ],
              ),
            ),
            Expanded(
                child:
                Text(totalTxt)),
//                  InkWell(
//                    onTap: (){
//                      // 带分割线不带背景
//                      JhPopMenus.show(context, clickCallback: (index, selText) {
//                        print('选中index: ${index}');
//                        print('选中text: ${selText}');
//
//
//                      });
//                    },
//                    child: Padding(
//                      padding: EdgeInsets.symmetric(horizontal: 20),
//                      child: Image.asset(
//                        'assets/shaixuan.png',
//                        width: 15,
//                        height: 15,
//                      ),
//                    ),
//                  ),
          ],
        ),
      );
    });
  }
  ///筛选时间
  void updateTime() {
    MyPicker.showPicker(
      context: context,
      current: date,
      end: end,
      mode: MyPickerMode.month,
      onConfirm: _change('yyyy-MM'),
    );
  }

  _change(formatString) {
    return (_date) {
      date = _date;
      dateStr = MyDate.format(formatString, _date);
      page=1;
      _fetchData();
      context.read<Bill>().changeDateStr(dateStr,'1');
    };
  }
  Container buildEmptyContainer() {
    return Container(
      color: Colors.white,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              'assets/v3_nodata.png',
              width: 100,
              height: 100,
            ),
            Text(
              '暂无明细',
              style: TextStyle(color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }

  SmartRefresher buildSmartRefresher(Widget child) {
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: items.length != 0,
      controller: _refreshController,
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: child,
    );
  }

  @override
  bool get wantKeepAlive => true;
}
// ignore: must_be_immutable
class _RechargeStickyHeaderList extends StatelessWidget {
  _RechargeStickyHeaderList({
    Key key,
    this.index,
    this.title,
    this.list,
    this.sections,
  }) : super(key: key);

  final int index;
  final String title;
  final List<RechargeRecordEntity> list;
  final Map<String, List<RechargeRecordEntity>> sections;
  List<double> inList=[];
  int firstIndex=-1;
  var totalTxt='';

  @override
  Widget build(BuildContext context) {
    list.forEach((element) {
      inList.add(element.payMoney);
    });
    totalTxt='总充值￥${inList.sum.toStringAsFixed(2)}';
    return SliverStickyHeader.builder(
      sticky: false,
      builder: (context, state) {
        if(state.scrollPercentage==0&&index==firstIndex){
          Future.delayed(Duration(microseconds: 1000)).then((value){
            if (index>0) {
              context.read<Bill>().changeDateStr(sections.keys.toList()[index-1],'1');
            }
          });
        }
        if(state.scrollPercentage>0){
          firstIndex=index;
          Future.delayed(Duration(microseconds: 1000)).then((value){
            context.read<Bill>().changeDateStr(title,'1');
          });
        }
        print('title:$title isPinned:${state.isPinned}  scrollPercentage:${state.scrollPercentage}');
        return Visibility(
          visible: index!=0,
          child: Container(
            color: Colors.white,
            padding: EdgeInsets.all(10),
            child: Row(
              children: [
                Text(title, style: TextStyle(color: Colors.blue)),
                Container(width: 2,height: 12,color: Colors.grey,margin: EdgeInsets.symmetric(horizontal: 5),),
                Expanded(
                  child:
                  Text(totalTxt,style: TextStyle(color: Colors.grey)),
                )
              ],
            ),
          ),
        );
      },
      sliver: SliverList(
        delegate: SliverChildBuilderDelegate(
          buildCard,
          childCount: list.length,
        ),
      ),
    );
  }
  Widget buildCard(BuildContext c, int i) {
    RechargeRecordEntity bill = list[i];
    return Column(
      children: [
        Container(
          color: Colors.white,
          padding: EdgeInsets.symmetric(vertical: 5,horizontal: 10),
          child: Row(
            children: [
              Container(
                  width: 30,
                  height: 30,
                  decoration: BoxDecoration(
                      color: Color(0xffF9951D),
                      borderRadius: BorderRadius.all(Radius.circular(15))
                  ),
                  child: Center(child: Text('充',style: TextStyle(color: Colors.white),))
              ),
              SizedBox(width: 10,),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(bill.stateName),
                    SizedBox(height: 5,),
                    Text(bill.createTime.replaceAll('T', ' '),style: TextStyle(color: Color(0xffC2C2C2)),),
                  ],
                ),
              ),
              SizedBox(width: 10,),
              Text('+${bill.payMoney}',style: TextStyle(color: Color(0xffF9951D)),)
            ],
          ),
        ),
        Visibility(
            visible: i!=list.length-1,
            child: Divider(height: 1,))
      ],
    );
  }
}

class BillSubPage extends StatefulWidget {
  final String state;

  BillSubPage(this.state);

  @override
  _BillSubPageState createState() => _BillSubPageState();
}

class _BillSubPageState extends State<BillSubPage>
    with AutomaticKeepAliveClientMixin {

  var date = DateTime.now();
  var end = DateTime.now();
  var dateStr = MyDate.format('yyyy-MM', DateTime.now());
  var totalTxt='';

  var page = 1;
  var limit = 10;
  List<FinanceEntity> items = [];
  Map<String, List<FinanceEntity>> sections=Map();
  List<double> inList=[];
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
    _fetchData();
    print("BillSubPage重绘了");
  }

  void _fetchData() {
    FinancesJsonEntity financeJson=FinancesJsonEntity();
    financeJson.page=page;
    financeJson.state=widget.state;
    financeJson.limit=limit;
    financeJson.userID=Api.userName;
    RequestUtil.post(Api.financesFactoryGetOrderList, financeJson.toJson()).then((value) => this.setState(() {
          List list = value['Data']['Table'];
          List<FinanceEntity> financeEntityList = [];
          list.forEach((element) {
            financeEntityList.add(financeEntityFromJson(FinanceEntity(),element));
          });
          if (page == 1) {
            items = financeEntityList;
            _refreshController.resetNoData();
          } else {
            if (financeEntityList.length == 0) {
              _refreshController.loadNoData();
            } else {
//              Year=2021;
//              Month=12-page;
//              for(int i=0;i<10;i++){
//                items.add(Bill(BillSecEntity.init(24244, 0, '', '2424420210416115558', '$Year-$Month-16 11:55:58', (10+i).toDouble(), '收入', '2', false),false));
//              }
              items.addAll(financeEntityList);
            }
          }
          ///按月份分组
          sections = groupBy(items, (financeEntity) => financeEntity.createDate.substring(0,financeEntity.createDate.lastIndexOf('-')));
        }));
  }

  @override
  void dispose() {
    print('dispose');
    _refreshController.dispose();
    super.dispose();
  }
  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  void _onRefresh() async {
    await Future.delayed(Duration(milliseconds: 1000));
    page = 1;
    _fetchData();
    _refreshController.resetNoData();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    await Future.delayed(Duration(microseconds: 1000));

    page++;
    _fetchData();
    _refreshController.loadComplete();
  }


  @override
  Widget build(BuildContext context) {
    super.build(context); //必须实现 不然 在push过后页面会刷新
    return buildBody();
  }

  Widget buildBody() {
    return DefaultStickyHeaderController(
      child: Container(
        padding: EdgeInsets.only(top: 10),
        color: ColorsUtil.hexToColor('#F2F2F2'),
        child: Column(
          children: [
            Consumer<Bill>(builder: (context,provider,child){
              inList.clear();
              var date=provider.dateStr;
              var billState=provider.billState;
              if(date!=null&&widget.state==billState){
                dateStr=date;
                if (sections[dateStr]!=null) {
                  sections[dateStr].forEach((e) {
                    inList.add(billState=='23'?(e.payMoney==null?0:e.payMoney):(e.settlementMoney==null?0:e.settlementMoney));
                  });
                }
                switch(widget.state){
                  case '23':
                    totalTxt='总冻结￥${inList.sum.toStringAsFixed(2)}';
                    break;
                  case '2':
                    totalTxt='';
                    break;
                  case '3':
                    totalTxt='总支出￥${inList.sum.toStringAsFixed(2)}';
                    break;
                }
              }
             return Container(
               color: Colors.white,
               padding: EdgeInsets.all(10),
               child: Row(
                 children: [
                   InkWell(
                     onTap: updateTime,
                     child: Row(
                       children: [
                         Text(dateStr, style: TextStyle(color: Colors.blue)),
                         Icon(
                           Icons.arrow_drop_down,
                           color: Colors.blue,
                         )
                       ],
                     ),
                   ),
                   Expanded(
                       child:
                       Text(totalTxt)),
//                  InkWell(
//                    onTap: (){
//                      // 带分割线不带背景
//                      JhPopMenus.show(context, clickCallback: (index, selText) {
//                        print('选中index: ${index}');
//                        print('选中text: ${selText}');
//
//
//                      });
//                    },
//                    child: Padding(
//                      padding: EdgeInsets.symmetric(horizontal: 20),
//                      child: Image.asset(
//                        'assets/shaixuan.png',
//                        width: 15,
//                        height: 15,
//                      ),
//                    ),
//                  ),
                 ],
               ),
             );
            }),
            Expanded(
              child: items.length == 0
                  ? buildSmartRefresher(buildEmptyContainer())
                  : buildSmartRefresher(CustomScrollView(
                slivers: sections.keys.toList().asMap().keys.map((index) => _StickyHeaderList(billState:widget.state,sections: sections,index: index,list: sections[sections.keys.toList()[index]],title: sections.keys.toList()[index])).toList(),
              )),
            )
          ],
        ),
      ),
    );
  }
  ///筛选时间
  void updateTime() {
    MyPicker.showPicker(
      context: context,
      current: date,
      end: end,
      mode: MyPickerMode.month,
      onConfirm: _change('yyyy-MM'),
    );
  }

  _change(formatString) {
    return (_date) {
        date = _date;
        dateStr = MyDate.format(formatString, _date);
        page=1;
        _fetchData();
        context.read<Bill>().changeDateStr(dateStr,widget.state);
    };
  }
  Container buildEmptyContainer() {
    return Container(
      color: Colors.white,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              'assets/v3_nodata.png',
              width: 100,
              height: 100,
            ),
            Text(
              '暂无明细',
              style: TextStyle(color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }

  SmartRefresher buildSmartRefresher(Widget child) {
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: items.length != 0,
      controller: _refreshController,
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: child,
    );
  }

  @override
  bool get wantKeepAlive => true;
}


class _StickyHeaderList extends StatelessWidget {
  _StickyHeaderList({
    Key key,
    this.billState,
    this.index,
    this.title,
    this.list,
    this.sections,
  }) : super(key: key);

  final String billState;
  final int index;
  final String title;
  final List<FinanceEntity> list;
  final Map<String, List<FinanceEntity>> sections;
  List<double> inList=[];
  int firstIndex=-1;
  var totalTxt='';

  @override
  Widget build(BuildContext context) {
    inList.clear();
    if (list!=null) {
      list.forEach((e) {
        inList.add(billState=='23'?(e.payMoney==null?0:e.payMoney):(e.settlementMoney==null?0:e.settlementMoney));
      });
    }
    switch(billState){
      case '23':
        totalTxt='总冻结￥${inList.sum.toStringAsFixed(2)}';
        break;
      case '2':
        totalTxt='';
        break;
      case '3':
        totalTxt='总支出￥${inList.sum.toStringAsFixed(2)}';
        break;
    }
    return SliverStickyHeader.builder(
      sticky: false,
      builder: (context, state) {
        if(state.scrollPercentage==0&&index==firstIndex){
          Future.delayed(Duration(microseconds: 1000)).then((value){
            if (index>0) {
              context.read<Bill>().changeDateStr(sections.keys.toList()[index-1],billState);
            }
          });
        }
        if(state.scrollPercentage>0){
          firstIndex=index;
          Future.delayed(Duration(microseconds: 1000)).then((value){
            context.read<Bill>().changeDateStr(title,billState);
          });
        }
        print('title:$title isPinned:${state.isPinned}  scrollPercentage:${state.scrollPercentage}');
        return Visibility(
         visible: index!=0,
         child: Container(
           color: Colors.white,
           padding: EdgeInsets.all(10),
           child: Row(
             children: [
               Text(title, style: TextStyle(color: Colors.blue)),
               Container(width: 2,height: 12,color: Colors.grey,margin: EdgeInsets.symmetric(horizontal: 5),),
               Expanded(
                 child:
                 Text(totalTxt,style: TextStyle(color: Colors.grey)),
               )
             ],
           ),
         ),
       );
      },
      sliver: SliverList(
        delegate: SliverChildBuilderDelegate(
              buildCard,
          childCount: list.length,
        ),
      ),
    );
  }
  Widget buildCard(BuildContext c, int i) {
    FinanceEntity bill = list[i];
    var title='';
    var money='0';
    var color=Color(0xffF9951D);
    switch(billState){
      case '23':
        title='冻';
        money='-${bill.payMoney==null?'0':bill.payMoney}';
        color=Colors.red;
        break;
      case '2':
        title='待';
        break;
      case '3':
        title='已';
        money='-${bill.settlementMoney==null?'0':bill.settlementMoney}';
        color=Colors.red;
        break;
    }
    return Column(
      children: [
        InkWell(
          onTap: (){
            push(c, OrderDetailPage(bill.orderID));
          },
          child: Container(
            color: Colors.white,
            padding: EdgeInsets.symmetric(vertical: 5,horizontal: 10),
            child: Row(
              children: [
                Container(
                    width: 30,
                    height: 30,
                    decoration: BoxDecoration(
                        color: color,
                        borderRadius: BorderRadius.all(Radius.circular(15))
                    ),
                    child: Center(child: Text(title,style: TextStyle(color: Colors.white),))
                ),
                SizedBox(width: 10,),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('工单号：${bill.orderNumber}'),
                      SizedBox(height: 5,),
                      Text(bill.createDate.replaceAll('T', ' '),style: TextStyle(color: Color(0xffC2C2C2)),),
                    ],
                  ),
                ),
                SizedBox(width: 10,),
                Visibility(
                  visible: billState!='2',
                    child: Text(money,style: TextStyle(color: color),))
              ],
            ),
          ),
        ),
        Visibility(
            visible: i!=list.length-1,
            child: Divider(height: 1,))
      ],
    );
  }
}